import { checkIfLogin } from '../../utils/check'
import { wxlogin, getInfo, loginAgain } from '../../services/profile'
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo:{},
    sexStr: "",
    code:""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // const tempUserInfo = app.globalData.userInfo || wx.getStorageSync('userInfo') || {}
    // this.setData({
    //   userInfo: tempUserInfo
    // })
    
  },

  onShow(){
    checkIfLogin()
    this.getCode()
    // const tempUserInfo = app.globalData.userInfo || wx.getStorageSync('userInfo') || {}
    // this.setData({
    //   userInfo: tempUserInfo
    // })
    // this.getUserProfile()
    this.handleGetInfo()
  },

  getCode(){
    wx.login({
      success: res => {
        console.log("userinfo>loginRes>>>", res)
        wx.setStorageSync('code', res.code)
        this.setData({
          code: res.code
        })
      }
    })
  },


  handleExit(){
    // wx.removeStorageSync('token')
    // wx.removeStorageSync('userInfo')
    // wx.removeStorageSync('appid')
    // wx.removeStorageSync('secret')
    // if(wx.getStorageSync('spaceId')){
    //   wx.removeStorageSync('spaceId')
    // }
    wx.clearStorage()
    app.globalData.userInfo = null
    wx.reLaunch({
      url: '/pages/home-page/home-page',
    })
  },

  handleToggle(){
    wx.clearStorage()
    app.globalData.userInfo = null
  },

  async handleGetInfo(){
    let resInfo = await getInfo()
    if(resInfo.code === 200){
      let userInfo = resInfo.user
      let sexStr = ""
      if(userInfo.sex == 0){
        sexStr = '男'
      } else if(userInfo.sex == 1){
        sexStr = '女'
      }

      this.setData({
        userInfo,
        sexStr
      })
    }
  },

  getPhoneNumber (e) {
    const code = this.data.code || ""
    const encryptedData = e.detail.encryptedData
    const iv = e.detail.iv
    wx.clearStorage()

    wxlogin({code, encryptedData, iv, type:"0"}).then(res => {
      console.log("loginRes>>>",res)
      if(res.code === 200){
        const token = res.data.access_token
        wx.setStorageSync('token', token)
        loginAgain().then(loginAginRes => {
          console.log("loginAginRes>>>", loginAginRes)
          wx.setStorageSync('appid', loginAginRes.data.appid || "")
          wx.setStorageSync('secret', loginAginRes.data.secret || "")
          wx.setStorageSync('token', loginAginRes.data.access_token)
          getInfo().then(InfoRes=>{
            console.log("InfoRes>>>", InfoRes)
            if(InfoRes.code === 200){
              wx.setStorageSync('userInfo', InfoRes.user)
              app.globalData.userInfo = InfoRes.user
              // wx.switchTab({
              //   url: '/pages/home-page/home-page',
              // })
              wx.reLaunch({
                url: '/pages/home-page/home-page',
              })
            }
          })
        })
      }
    })
  },

})